const express = require('express');
const app = express();
const bodyParser = require('body-parser');


const fw = require('./core/framework');

const utils = require('./core/utils');
const AI = require('./AI/IndexAnalysis');

const urlencodedParser = bodyParser.json();
const Biz = require('./biz/index');
const router = express.Router();
const API = require('./api/index');
const DB = require('./db/index');

// AI.findAlarmContactGroupAndUsers(2,function(r1,r2){
//     console.log('------rr222--->',r1,r2);
// })

// 定义局部变量
let ioUser = {}; // socket连接的用户
let __socket = null;

app.use(express.static(__dirname + '/public'));
API.init(router, urlencodedParser);

router.post('/alarmEvent/push', urlencodedParser, function (req, res) {
    let param = fw.utils.parseBody(req);
    AI.analysisIndex(param);
    res.send({code: 0})
});

router.post('/face/eigenValue/send', urlencodedParser, function (req, res) {
    let param = fw.utils.parseBody(req);
    console.log('eigenValue===>', param);
    let deviceUser = ioUser['device_' + param.device_id];
    if (deviceUser) {
        if (param.face_eigen_value) {
            deviceUser.send(JSON.stringify({
                code: 0,
                data: {
                    device_id: param.device_id,
                    face_id: param.face_id,
                    status: param.status,
                    face_eigen_value: param.face_eigen_value
                }
            }))
        } else {
            deviceUser.send(JSON.stringify({
                code: 0,
                data: {
                    device_id: param.device_id,
                    face_id: param.face_id,
                    status: 0,
                    msg: '请靠近摄像头后重试'
                }
            }))
        }
        res.send({code: 0})
    } else {
        res.send({code: -1, msg: '设备' + param.device_id + '的连接已断开'});
    }
});

router.post('/device/groundEigenValue/send', urlencodedParser, function (req, res) {
    let param = fw.utils.parseBody(req);
    console.log('groundEigenValue===>', param);
    let deviceUser = ioUser['device_' + param.device_id];
    if (deviceUser) {
        if (param.status == 1) {
            deviceUser.send(JSON.stringify({
                code: 0,
                data: {
                    device_id: param.device_id,
                    status: 1
                }
            }))
        } else {
            deviceUser.send(JSON.stringify({
                code: 0,
                data: {
                    device_id: param.device_id,
                    status: 0,
                    ground_eigen_value: param.ground_eigen_value
                }
            }))
        }
        res.send({code: 0})
    } else {
        res.send({code: -1, msg: '设备' + param.device_id + '的连接已断开'});
    }
});

// 测试推送数据
// (function () {
//     console.log('==================收到事件数据----1------====================')
//     AI.analysisIndex({
//         device_id: 4,
//         face_id: 2,
//         index_name: 'fall',
//         index_value: true,
//         video_url: ''
//     });
// })();


var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 8181});
wss.on('connection', function (ws, req) {
    let params = req.url.substr(1).split('/');
    let type = (params[1] + '').toLowerCase();
    let id = params[0];
    let user = type + '_' + id;
    if (!(type == 'ai' || type == 'device')) {
        ws.send(JSON.stringify({code: 403, data: {msg: '非法链接'}}));
        ws.close();
        return false;
    }
    if (params.length > 0) {
        if (ioUser[user]) {
            ioUser[user].close();
            delete ioUser[user];
        }
        ioUser[user] = ws;
        console.log('用户' + user + '已保存')
    }
    console.log('userID===============>', req.url);
    // ioUser[userID] = ws;
    ws.on('message', function (message) {
        let msg, msgData, method;
        try {
            msg = typeof message == 'string' ? message : JSON.stringify(message);
            msgData = JSON.parse(msg);
            method = msgData.method | 0;
        } catch (e) {
            console.log('解析接入数据发生异常', message);
            ws.send(JSON.stringify({code: '600', data: {msg: '传入的数据格式错误，非json格式'}}));
            return false;
        }
        switch (type) {
            case 'ai':
                try {
                    if (method == 1000) {
                        let deviceUser = 'device_' + msgData.data.device_id;
                        if (ioUser[deviceUser]) {
                            // console.log(user + '向device服务'+msgData.data.device_id+'发送信息', msg);
                            ioUser[deviceUser].send(msg);
                        } else {
                            ws.send(JSON.stringify({
                                code: 0,
                                method: 1000,
                                data: {
                                    status: 0
                                }
                            }));
                        }
                    }else {
                        ws.send(JSON.stringify({code: 404, data: {msg: '目前只处理骨架图的实时数据。请注意method参数，其它用http请求。'}}))
                    }
                    // let aiData = msg.split(' ');
                    // if (ioUser[aiData[0]]) {
                    //     // console.log('m1的用户登录了');
                    //     ioUser[aiData[0]].send(msg);
                    // } else {
                    //     ws.send([-1, 1, aiData[0], ''].join(' '));
                    // }
                } catch (e) {
                    console.log('ai的信息发送到设备' + ((msgData || {}).data || {}).device_id + '发生异常', e);
                }
                break;
            case 'device':
                try {
                    let aiUser = 'ai_' + method;
                    if (ioUser[aiUser]) {
                        console.log(user + '向Ai服务' + method + '发送信息', msg);
                        ioUser[aiUser].send(msg);
                    } else {
                        ws.send(JSON.stringify({code: 404, data: {msg: 'ai服务' + method + '未连接'}}));
                    }
                } catch (e) {
                    ws.send(JSON.stringify({code: 400, data: {msg: '发送到ai服务' + method + '发生异常'}}));
                    console.log('-404 设备发送到AI发生异常', e);
                }
                break;
            default:
                break;
        }
        // console.log('===user->'+user+'<--->' + message + '<===');
    });

    ws.on("close", function () {
        if (ioUser[user]) {
            ioUser[user].close();
            delete ioUser[user];
        }
        console.log('检测到用户' + user + '连接已断开')
    });

    ws.on("error", function (err) {
        if (ioUser[user]) {
            ioUser[user].close();
            delete ioUser[user];
        }
        console.log('检测到用户' + user + '连接发生异常');
    });

});


module.exports = {
    router: router
};
